<?php 
namespace app\workerman\controller;
use app\BaseController;
use think\facade\Db;
use app\common\logic\SmsApiLogic;
use app\common\logic\MemberAccountLogic;
use app\common\logic\SmsOrderLogic;

class Timer extends BaseController{
	//获取短信
	public function getSms(){
		//获取所有订单，已经支付的订单，未获取到短信的订单，未拉黑的订单，未释放的订单
		$list = Db::name('order_sms')
				->alias('os')
				->field('os.*, cc.channel_type')
                ->join('channel_country cc','cc.id=os.country_id')
				->where('os.status', 20)
				->where('os.ban_status', 10)
				->where('os.denial_status', 10)
				// ->where('sms_status', 10)
				->order('id asc')
				->select()->toArray();
		if($list){
			foreach($list as $k=>$v){
				//时间判断，如果超时，执行一次获取短信操作。如果获取到了，则直接修改为已接收到短信。
				$outTime = 600 - (time()-strtotime($v['pay_time']));
				sys_log($v['id']."==".$outTime.'=='.(time()-strtotime($v['pay_time'])).'==600','ake.log');
				//未收到短信则执行api获取短信
				if($v['sms_status']==10){
					//如果未收到短信，则退款并释放。
					$rs = SmsApiLogic::getSms('get_sms', $v);
					sys_log(json_encode($rs),"engao.log");
					$tmp = [];
					//短信获取到了
					if(isset($rs['response'])){
						if($rs['response']==1 || $rs['response']==4){
							$tmp['sms_code'] = isset($rs['sms'])?$rs['sms']:"";
							$tmp['sms_content'] = isset($rs['text'])?$rs['text']:'';
							$tmp['sms_status'] = 20;
							Db::name('order_sms')->where('id', $v['id'])->update($tmp);
						}
					}elseif($v['channel_id']==3){
						if(isset($rs[0]) && isset($rs[0]['msg']) && $rs[0]['msg']){
							$tmp['sms_code'] = $rs[0]['msg'];
							$tmp['sms_content'] = "sms code：".$rs[0]['msg'];
							$tmp['sms_status'] = 20;
							Db::name('order_sms')->where('id', $v['id'])->update($tmp);
						}
					}

				}
				//直接释放
				sys_log("age",'sfla.log');
				if($outTime<=0){
					sys_log("age3",'sfla.log');
					$tmp = [];
					$tmp['denial_status'] = 20;
					$tmp['denial_content'] = "系统释放";
					$tmp['exp_time'] = date('Y-m-d H:i:s');
					// sys_log(json_encode($tmp),'sfla.log');
					Db::name('order_sms')->where('id', $v['id'])->update($tmp);
					$sf = SmsApiLogic::denial('denial', $v);
				}else{
					sys_log($outTime,'sfla.log');
				}
				
				sys_log("定时器执行记录id:".$v['id']);
			}
		}
	}

	//释放退款定时器
	public function denialAndBanRefund(){
		$list = Db::name('order_sms')
				->where('status', 20)
				->where('sms_status', 10)
				->where('ban_status|denial_status', 20)
				->order('id asc')
				->select()
				->toArray();

		if($list){
			foreach($list as $k=>$v){
				//开启事务
		        Db::startTrans();
		        try {
					//API取消成功了，修改订单状态，退款
					$rs2 = MemberAccountLogic::init()->refAccountIn($v);
					$rs3 = SmsOrderLogic::init()->refundOrder($v, 90);
					if(!$rs2 || !$rs3){
						Db::rollback();
					}
					Db::commit();
		        } catch (\Exception $e) {
		            // print_r($e->getMessage());
		            // 回滚事务
		            Db::rollback();
		        }
			}
		}
	}

	//用户升降级定时器
	public function shengjiangji(){
		$year = date('Y');
		$mouth = date('m');
		if($mouth=="01"){
			$year = $year-1;
			$mouth = "12";
		}else{
			$mouth = $mouth-1;
			if($mouth<10){
				$mouth = "0".$mouth;
			}
		}
		//获取列表
		$lists = Db::name('member_recharge_year_mouth')
					->alias('r')
					->field('r.*, m.grade_level')
					->join('member m','m.id=r.member_id')
					->where('r.year', $year)
					->where('r.mouth', $mouth)
					->where('r.has_to_level', 0)
					->select()->toArray();
		// print_r($lists);exit;
		if(!$lists){
			return;
		}

		foreach($lists as $v){
			//等级改变，开启事务
			Db::startTrans();
			try {
				$dm = [];
				$dm['member_id'] = $v['member_id'];
				$dm['current_level'] = $v['grade_level'];
				$dm['after_level'] = $v['current_level'];
				$dm['create_time'] = date('Y-m-d H:i:s');
				$rs = Db::name('member_log')->insert($dm);
				if(false!==$rs){
					//新增失败，事务回滚
					Db::rollback();
				}
				$rs2 = Db::name('member')->where('id', $v['member_id'])->update(['grade_level'=>$v['current_level']]);
				if(false!==$rs2){
					//更新失败，回滚
					Db::rollback();
				}

				$rs3 = Db::name('member_recharge_year_mouth')
						->where('id', $v['id'])
						->update(['has_to_level'=>1]);
				if(false!==$rs3){
					//更新失败，回滚
					Db::rollback();
				}
				//成功，提交
				Db::commit();
			} catch (\Exception $e) {
			    // 回滚事务
			    Db::rollback();
			}
		}
	}

	//获取电话号码
	public function getPhone(){
		sys_log("来了",'laile.txt');
		// echo '<pre>';
		$list = Db::name('order_sms')
				->field('id,channel_id,order_sn,country_code,server_code,api_id,phone,server_id,country_id,api_key')
				->where('status', 20)
				->where('ban_status', 10)
				->where('denial_status', 10)
				->where('sms_status', 10)
				->where('phone','exp','is null')
				->where('api_id','exp','is not null')
				->order('id asc')
				->select()
				->toArray();
		// print_r($list);exit;
		// sys_log(json_encode($list),'laile.txt');
		if($list){
			foreach($list as $k=>$v){
				$rs = SmsApiLogic::getPhone('get_phone', $v);
				if(isset($rs[0]) && isset($rs[0]['number'])){
					$data = [];
					$data['phone'] = $rs[0]['number'];
					Db::name('order_sms')->where('id', $v['id'])->update($data);
				}
			}
		}
		return;
	}

}


// Array ( 
// [0] => Array ( 
// [country] => 380 
// [sum] => 3 
// [service] => 1xbet 
// [number] => +380665110013 
// [response] => TZ_NUM_WAIT 
// [tzid] => 42085562 [time] => 820 
// [form] => index ) )